import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { map } from 'rxjs/operators';

import { GetLastURL } from '../../services/last-url.service';

@Component({
    selector: 'm-human-tab',
    templateUrl: './human-tab.component.html',
    styleUrls: ['./human-tab.component.scss']
})
export class HumanTabComponent implements OnInit {
    humanButtons = [
        { link: '/logs/human/pc', name: '终端使用日志' },
        { link: '/logs/human/software', name: '软件使用日志' }
    ];

    constructor(private route: ActivatedRoute,
        private router: Router) { }

    areaList$ = this.route.data.pipe(map(data => data['zone_list']));
    activeAreaID: number;
    searchKey: string = '';

    ngOnInit() {
        this.route.queryParamMap.subscribe(data => {
            this.activeAreaID = +(data.get('area_id') || 0);
            this.searchKey = data.get('keywords') || '';
        })
    }

    onActiveAreaID(id: number) {
        if (this.activeAreaID == id) {
            return;
        }
        this.activeAreaID = id;
        this.startSearch();
    }

    onSearchKey(key: string, exec: boolean) {
        if (this.searchKey == key) {
            return;
        }
        this.searchKey = key;
        if (!exec) {
            return;
        }
        this.startSearch();
    }

    startSearch() {
        let params = { page: 1 };
        if (this.activeAreaID != 0) {
            params['area_id'] = this.activeAreaID;
        }
        if (this.searchKey.length != 0) {
            params['keywords'] = this.searchKey;
        }
        this.router.navigate([GetLastURL(this.route)], {
            relativeTo: this.route,
            queryParams: params
        })
    }
}
